<template>
  <div class="assignments-container">
    <div class="page-header">
      <h3>作业管理</h3>
    </div>

    <el-tabs v-model="activeTab">
      <el-tab-pane label="待完成作业" name="pending">
        <el-table :data="pendingAssignments" style="width: 100%" v-loading="loading">
          <el-table-column prop="title" label="作业标题"></el-table-column>
          <el-table-column prop="course" label="课程"></el-table-column>
          <el-table-column prop="teacher" label="教师"></el-table-column>
          <el-table-column prop="deadline" label="截止日期" width="180"></el-table-column>
          <el-table-column label="操作" width="150">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" @click="handleSubmit(scope.row)">提交作业</el-button>
              <el-button size="mini" @click="handleView(scope.row)">查看详情</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="已完成作业" name="completed">
        <el-table :data="completedAssignments" style="width: 100%" v-loading="loading">
          <el-table-column prop="title" label="作业标题"></el-table-column>
          <el-table-column prop="course" label="课程"></el-table-column>
          <el-table-column prop="teacher" label="教师"></el-table-column>
          <el-table-column prop="submitTime" label="提交时间" width="180"></el-table-column>
          <el-table-column prop="score" label="分数" width="100">
            <template slot-scope="scope">
              <span v-if="scope.row.status === '已批改'">{{ scope.row.score }}</span>
              <el-tag v-else type="info">待批改</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template slot-scope="scope">
              <el-button size="mini" @click="handleView(scope.row)">查看详情</el-button>
              <el-button 
                size="mini" 
                type="primary"
                @click="handleResubmit(scope.row)"
                v-if="scope.row.status !== '已批改'">重新提交</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>

    <!-- 提交作业对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="submitDialogVisible" width="50%">
      <el-form :model="form" :rules="rules" ref="form" label-width="80px">
        <el-form-item label="作业要求">
          <div class="assignment-description">{{ currentAssignment.description }}</div>
        </el-form-item>
        <el-form-item label="附件" v-if="currentAssignment.attachments && currentAssignment.attachments.length > 0">
          <div class="attachment-list">
            <div v-for="file in currentAssignment.attachments" :key="file.url" class="attachment-item">
              <i class="el-icon-document"></i>
              <span>{{ file.name }}</span>
              <el-button type="text" @click="downloadAttachment(file.url)">下载</el-button>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="上传作业" prop="file">
          <el-upload
            action="#"
            :auto-upload="false"
            :file-list="fileList"
            :on-change="handleFileChange">
            <el-button size="small" type="primary">选择文件</el-button>
            <div slot="tip" class="el-upload__tip">支持 .doc, .docx, .pdf 格式，大小不超过 10MB</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="form.comment" :rows="3"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="submitDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAssignment" :loading="submitting">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 查看作业详情对话框 -->
    <el-dialog title="作业详情" :visible.sync="viewDialogVisible" width="50%">
      <div class="assignment-detail">
        <h4>{{ currentAssignment.title }}</h4>
        <p class="detail-item"><span class="label">课程：</span>{{ currentAssignment.course }}</p>
        <p class="detail-item"><span class="label">教师：</span>{{ currentAssignment.teacher }}</p>
        <p class="detail-item"><span class="label">截止日期：</span>{{ currentAssignment.deadline }}</p>
        <p class="detail-item"><span class="label">作业要求：</span></p>
        <div class="description">{{ currentAssignment.description }}</div>
        
        <template v-if="currentAssignment.status === '已提交' || currentAssignment.status === '已批改'">
          <div class="submission-info">
            <h5>提交信息</h5>
            <p class="detail-item"><span class="label">提交时间：</span>{{ currentAssignment.submitTime }}</p>
            <p class="detail-item"><span class="label">状态：</span>{{ currentAssignment.status }}</p>
            <p class="detail-item" v-if="currentAssignment.status === '已批改'">
              <span class="label">分数：</span>{{ currentAssignment.score }}
            </p>
            <p class="detail-item" v-if="currentAssignment.status === '已批改'">
              <span class="label">教师评语：</span>{{ currentAssignment.teacherComment || '无' }}
            </p>
            <p class="detail-item" v-if="currentAssignment.fileUrl">
              <span class="label">提交文件：</span>
              <el-button type="text" @click="downloadAttachment(currentAssignment.fileUrl)">
                下载文件
              </el-button>
            </p>
          </div>
        </template>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { 
  getStudentAssignmentStats, 
  getStudentAssignmentDetail, 
  uploadAssignmentFile, 
  submitAssignment
} from '@/api/student'
import { mapGetters } from 'vuex'

export default {
  name: 'StudentAssignments',
  data() {
    return {
      loading: false,
      submitting: false,
      activeTab: 'pending',
      pendingAssignments: [],
      completedAssignments: [],
      submitDialogVisible: false,
      viewDialogVisible: false,
      dialogTitle: '',
      currentAssignment: {},
      form: {
        file: null,
        comment: ''
      },
      fileList: [],
      rules: {
        file: [
          { required: true, message: '请上传作业文件', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters(['userInfo']),
    studentId() {
      return this.userInfo.studentId || localStorage.getItem('studentId')
    }
  },
  created() {
    this.getAssignments()
  },
  methods: {
    getAssignments() {
      this.loading = true
      
      getStudentAssignmentStats(this.studentId)
        .then(response => {
          if (response.code === 200) {
            // 处理作业数据
            const assignments = response.data || []
            this.pendingAssignments = assignments
              .filter(item => item.status === '未提交')
              .map(item => this.formatAssignment(item))
            
            this.completedAssignments = assignments
              .filter(item => item.status === '已提交' || item.status === '已批改')
              .map(item => this.formatAssignment(item))
          } else {
            this.$message.error(response.message || '获取作业列表失败')
          }
        })
        .catch(error => {
          console.error('获取作业列表失败:', error)
          this.$message.error('获取作业列表失败')
        })
        .finally(() => {
          this.loading = false
        })
    },
    formatAssignment(item) {
      return {
        id: item.assignmentId,
        allocationId: item.id,
        title: item.assignmentTitle,
        course: item.courseName,
        teacher: item.teacherName,
        deadline: item.deadline,
        submitTime: item.submitTime,
        status: item.status,
        score: item.score,
        description: item.description,
        attachments: item.attachments ? JSON.parse(item.attachments) : [],
        teacherComment: item.teacherComment,
        fileUrl: item.fileUrl
      }
    },
    handleSubmit(assignment) {
      this.dialogTitle = '提交作业'
      this.currentAssignment = assignment
      this.form = {
        file: null,
        comment: ''
      }
      this.fileList = []
      this.submitDialogVisible = true
    },
    handleResubmit(assignment) {
      this.dialogTitle = '重新提交作业'
      this.currentAssignment = assignment
      this.form = {
        file: null,
        comment: ''
      }
      this.fileList = []
      this.submitDialogVisible = true
    },
    handleView(assignment) {
      // 获取作业详情数据
      this.loading = true
      getStudentAssignmentDetail(assignment.id, this.studentId)
        .then(response => {
          if (response.code === 200) {
            this.currentAssignment = this.formatAssignment(response.data)
            this.viewDialogVisible = true
          } else {
            this.$message.error(response.message || '获取作业详情失败')
          }
        })
        .catch(error => {
          console.error('获取作业详情失败:', error)
          this.$message.error('获取作业详情失败')
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleFileChange(file, fileList) {
      this.fileList = fileList.slice(-1) // 只保留最后一个文件
      this.form.file = file.raw
    },
    // 下载附件
    downloadAttachment(fileUrl) {
      if (!fileUrl) {
        this.$message.warning('文件链接不存在')
        return
      }
      
      // 从URL获取原始文件名
      const originalFileName = this.getOriginalFileName(fileUrl)
      console.log('下载使用的文件名:', originalFileName)
      
      // 直接使用a标签的download属性实现下载
      const link = document.createElement('a')
      link.href = fileUrl
      link.setAttribute('download', originalFileName)
      link.target = '_blank'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      
      this.$message.success('文件下载已开始')
    },
    
    // 获取原始文件名
    getOriginalFileName(url) {
      if (!url) return '无文件名';
      
      try {
        // 格式1: 从name参数中获取Base64编码的原始文件名（阿里云OSS服务实现）
        const urlObj = new URL(url);
        const encodedName = urlObj.searchParams.get('name');
        
        if (encodedName) {
          // 解码BASE64编码的原始文件名
          try {
            // 使用window.atob解码BASE64字符串
            const base64Decoded = atob(encodedName);
            
            // 将UTF-8编码的字节转换为JavaScript字符串
            // 这种方法可以正确处理中文等非ASCII字符
            const bytes = new Uint8Array(base64Decoded.length);
            for (let i = 0; i < base64Decoded.length; i++) {
              bytes[i] = base64Decoded.charCodeAt(i);
            }
            const decodedName = new TextDecoder('utf-8').decode(bytes);
            
            console.log('从URL查询参数中解码的原始文件名:', decodedName);
            return decodedName;
          } catch (e) {
            console.error('BASE64解码失败:', e);
          }
        }
        
        // 格式2: 从其他可能的查询参数中获取原始文件名
        const filename = urlObj.searchParams.get('filename');
        if (filename) {
          return decodeURIComponent(filename);
        }
        
        // 格式3: 从路径中提取文件名
        const pathParts = urlObj.pathname.split('/');
        let fileName = pathParts[pathParts.length - 1];
        
        // 如果文件名包含查询参数，去除它们
        if (fileName.includes('?')) {
          fileName = fileName.split('?')[0];
        }
        
        // 尝试从文件名中提取原始名称
        const filenameMatch = fileName.match(/(.+)_\d+\.(\w+)$/) || fileName.match(/\d+_(.+)\.(\w+)$/);
        if (filenameMatch) {
          const extractedName = filenameMatch[1] + '.' + filenameMatch[2];
          console.log('从路径中提取的原始文件名:', extractedName);
          return extractedName;
        }
        
        return fileName || '未知文件';
      } catch (error) {
        console.error('解析URL失败:', error);
        return '未知文件';
      }
    },
    submitAssignment() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.submitting = true
          
          // 先上传文件获取URL
          uploadAssignmentFile(this.form.file)
            .then(response => {
              if (response.code === 200 && response.data) {
                const fileUrl = response.data
                
                // 提交作业
                return submitAssignment(this.currentAssignment.allocationId, {
                  fileUrl: fileUrl,
                  comment: this.form.comment
                })
              } else {
                throw new Error(response.message || '上传文件失败')
              }
            })
            .then(response => {
              if (response.code === 200) {
                this.$message.success('提交成功')
                this.submitDialogVisible = false
                this.getAssignments() // 重新获取作业列表
              } else {
                this.$message.error(response.message || '提交作业失败')
              }
            })
            .catch(error => {
              console.error('提交作业失败:', error)
              this.$message.error('提交作业失败: ' + (error.message || '未知错误'))
            })
            .finally(() => {
              this.submitting = false
            })
        }
      })
    }
  }
}
</script>

<style scoped>
.assignments-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h3 {
  margin: 0;
}

.assignment-description {
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  line-height: 1.6;
}

.attachment-list {
  margin-top: 10px;
}

.attachment-item {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
}

.attachment-item i {
  margin-right: 5px;
}

.attachment-item span {
  flex: 1;
}

.assignment-detail {
  padding: 20px;
}

.assignment-detail h4 {
  margin: 0 0 20px 0;
  font-size: 18px;
}

.detail-item {
  margin-bottom: 10px;
  line-height: 1.6;
}

.label {
  font-weight: bold;
  margin-right: 10px;
}

.description {
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  margin: 10px 0;
  line-height: 1.6;
}

.submission-info {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.submission-info h5 {
  margin: 0 0 15px 0;
  font-size: 16px;
}
</style> 